package com.flywen.utils;

import com.github.pagehelper.Page;
import com.flywen.exception.AppException;
import com.flywen.generic.GenericPageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class BeanConvert {
    private static final Logger LOGGER = LoggerFactory.getLogger(BeanConvert.class);

    public BeanConvert() {
    }

    public static <T> T convert(Object source, Class<T> destinationClass) {
        try {
            if (source != null) {
                T target = destinationClass.newInstance();
                BeanUtils.copyProperties(source, target);
                return target;
            } else {
                return null;
            }
        } catch (Exception var3) {
            LOGGER.error("convert error", var3);
            throw new AppException("9999", "bean convert fail");
        }
    }

    public static <T> List<T> convertList(Collection sourceList, Class<T> destinationClass) {
        if (sourceList == null) {
            return null;
        } else {
            List<T> destinationList = new ArrayList();
            Iterator var4 = sourceList.iterator();

            while(var4.hasNext()) {
                Object sourceObject = var4.next();
                T destinationObject = convert(sourceObject, destinationClass);
                destinationList.add(destinationObject);
            }

            return destinationList;
        }
    }

    public static <T> GenericPageResponse<List<T>> convertPage(Page sourcePage, Class<T> destinationClass) {
        if (sourcePage == null) {
            return null;
        } else {
            List<T> newList = convertList(sourcePage.getResult(), destinationClass);
            GenericPageResponse<List<T>> response = new GenericPageResponse();
            response.setObject(newList);
            response.setPages(sourcePage.getPages());
            response.setTotalCount(sourcePage.getTotal());
            return response;
        }
    }
}